<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="85%" :before-close="closeDelDialog" append-to-body>
      <el-row :gutter="20">
        <el-col :span="13">
          <el-form ref="fileForm" :model="fileForm" :rules="fileRules" label-width="80px" class="leftMain">
            <el-row>
              <el-col :span="24">
                <el-form-item label="件号" prop="fileNum">
                  <el-input v-model="fileForm.folderNum" style="width: 240px" placeholder="请输入" :disabled="true"></el-input> -
                  <el-input-number v-model="ziduanEnd" controls-position="right" style="width: 240px" :min="1" placeholder="请输入" @input="getfileNum"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="资料名" prop="genNume">
                  <el-input v-model="fileForm.genNume" placeholder="请输入" style="width: 85%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="页号" prop="pageHouse">
                  <el-input v-model="fileForm.pageHouse" placeholder="请输入" style="width: 240px" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="页数" prop="pageNum">
                  <el-input v-model="fileForm.pageNum" placeholder="请输入" style="width: 240px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出版单位" prop="publishUnit">
                  <el-input v-model="fileForm.publishUnit" placeholder="请输入" style="width: 240px" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="作者" prop="author">
                  <el-input v-model="fileForm.author" placeholder="请输入" style="width: 240px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出版日期" prop="publishData">
                  <el-date-picker v-model="fileForm.publishData" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期" style="width: 240px"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资料状况" prop="genStatus">
                  <el-input v-model="fileForm.genStatus" placeholder="请输入" style="width: 240px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- {{ isShowMj }} {{ isShowMj1 }} -->
              <el-col :span="12" v-show="isShowMj && isShowMj1">
                <el-form-item label="密级" prop="mj">
                  <el-select v-model="fileForm.mj" placeholder="请选择" clearable style="width: 240px">
                    <el-option v-for="(dict, index) in this.dict.type.MJ" :key="index" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="控制属性" prop="controlType">
                  <el-select v-model="fileForm.controlType" placeholder="请选择" clearable style="width: 240px" @change="changeControlType">
                    <el-option v-for="(dict, index) in this.dict.type.CONTROLTYPE" :key="index" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="fileForm.remark" type="textarea" placeholder="请输入" style="width: 85%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-row class="upLoadMain">
            <el-col :span="24" style="display: flex;">
              <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList"
                         :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
                         :show-file-list="false" :headers="headers" class="upload-file-uploader" ref="fileUpload">
                <!-- 上传按钮 -->
                　<el-button class="upload_btn" type="primary" icon="el-icon-upload">上传文件</el-button>
              </el-upload>
            </el-col>
            <el-col :span="24">
              <!-- 文件显示列表 -->
              <el-table :data="fileList" border  ref="reftableFile" :height="tableHeightFile"  stripe style="width: 100%;height: 220px;overflow: auto;" class="margin_top">
                <el-table-column label="序号" sortable align="center" type="index" prop="index" />
                <el-table-column label="文件名" align="center" prop="fieldName" :show-overflow-tooltip="true" />
                <el-table-column label="文件路径" align="center" prop="path" :show-overflow-tooltip="true" />
                <el-table-column label="文件大小" align="center" prop="docFileSize" :show-overflow-tooltip="true" />
                <el-table-column label="文件类型" align="center" prop="docFileType" :show-overflow-tooltip="true" />
                <el-table-column prop="address" label="操作" width="200px" align="center" header-align="center">
                  <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-delete"  plain @click="delTap(scope.row)" size="mini" title="删除"></el-button>
                    <el-button type="text" icon="el-icon-view"  plain @click="onPreviewTap(scope.row)" size="mini" title="预览"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="11">
          <!--
               文件预览
               1、修改添加文件预览istype="1"
               2、查看组件详情istype="2"
           -->
          <filePreviewTemplate v-if="item != ''" :item="item"></filePreviewTemplate>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDelDialog">取消</el-button>
        <el-button type="primary" @click="submitDetail">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import filePreviewTemplate from "@/views/information/receivingManagement/filePreviewTemplate"
import {getToken} from "@/utils/auth";
import {addFile, getFileDetail, updateFile} from "@/api/information/receivingManagement";  //文件预览模板
export default {
  name: "jianedit",
  props: ['open', 'openInfo'],
  archive_Dicts: ['MJ', 'CONTROLTYPE'],
  components: { filePreviewTemplate },
  data() {
    const checkFileNum = (rule, value, callback) => {
      if (value) {
        var reg = value.split('-')
        if (reg.includes('undefined')){
          callback(new Error('请输入全部件号'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      // 标题
      title: '',
      item: "",
      fileForm: {
        fileNum: undefined,
        folderNum: undefined,
        genNume: undefined,
        pageNum: undefined,
        pageHouse: undefined,
        publishUnit: undefined,
        author: undefined,
        publishData: undefined,
        genStatus: undefined,
        mj: undefined,
        controlType: undefined,
        remark: undefined
      },
      ziduanEnd: undefined,
      fileRules: {
        fileNum: [
          { required: true, message: "请输入件号" },
          { required: true, validator: checkFileNum }
        ],
        genNume: [
          { required: true, message: "请输入资料名" }
        ],
        controlType:  [
          { required: true, message: "请输入控制属性" }
        ]
      },


      uploadValue: undefined, //选择上传的文件
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/archive/collection/receive/upload",
      number: 0,
      // uploadFileUrl: process.env.VUE_APP_BASE_API + "/archive/lxjs/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      list: [],
      tableHeightFile: "220",
      // 卷层
      isShowMj: false,
      // 件层
      isShowMj1: false
    }
  },
  watch: {
    openInfo: {
      handler(valNew) {
        console.log(this.fileForm, valNew, '---------')
        if (valNew.controlType == '1') {
          this.isShowMj = true
          this.$set(this.fileForm, 'controlType', valNew.controlType)
          this.isShowMj1 = true
        } else {
          this.isShowMj = false
        }
        this.fileForm.folderNum = valNew.folderNum
        this.fileForm.fileNum = this.fileForm.folderNum + '-' + this.ziduanEnd
        this.fileForm.folderId = valNew.folderId
        if (valNew.ids == undefined) { //添加
          this.title = '件著录'
        } else {
          this.title = '件修改'
          //修改
          this.getUpdatefieldPost(valNew);
        }
      },
      immediate: true
    }
  },
  methods: {
    getfileNum() {
      this.fileForm.fileNum = this.fileForm.folderNum + '-' + this.ziduanEnd
    },
    getUpdatefieldPost(valNew) {
      getFileDetail(valNew.ids).then(response=>{
        this.fileForm = response.data
        var ziduan = response.data.fileNum.split('-')
        this.ziduanEnd = ziduan[ziduan.length - 1]
        this.fileList = response.data.efileList
        if (this.fileForm.controlType == '1') {
          this.isShowMj1 = true
        } else {
          this.isShowMj1 = false
        }
      })
    },
    changeMj(value) {
      for (let i = 0; i < this.dict.type.MJ.length; i++) {
        if (value == this.dict.type.MJ[i].value) {
          return this.dict.type.MJ[i].label
        }
      }
    },
    changeControlType(value) {
      var ct = ''
      for (let i = 0; i < this.dict.type.CONTROLTYPE.length; i++) {
        if (value == this.dict.type.CONTROLTYPE[i].value) {
          ct = this.dict.type.CONTROLTYPE[i].label
        }
      }
      if (ct == '控制') {
        this.isShowMj1 = true
      } else {
        this.isShowMj1 = false
      }
    },
    submitDetail() {
      this.$refs["fileForm"].validate(valid => {
        if (valid) {
          if (this.openInfo.controlType == '0') {
            if (this.fileForm.controlType != this.openInfo.controlType) {
              this.$modal.msgWarning('卷开放,卷内件必须开放')
              return
            }
          }
          this.mjLabel = this.changeMj(this.fileForm.mj)
          // console.log(this.mjLabel)
          if (this.isShowMj && this.isShowMj1) {
            if (this.fileForm.mj != undefined && this.mjLabel != '无秘') {
              if (this.fileForm.controlType != '1') {
                this.$modal.msgWarning('密级涉密,控制属性应该为控制')
                return
              }
            }
          } else {
            this.fileForm.mj = ''
          }
          if (this.openInfo.ids == undefined) { // 著录
            this.fileForm.efileList = this.fileList
            addFile(this.fileForm).then(response=>{
              this.$modal.msgSuccess("著录成功");
              this.fileList = []
              this.resetForm('fileForm')
              this.closeDelDialog()
            })
          } else {
            this.fileForm.efileList = this.fileList
            updateFile(this.fileForm).then(response=>{
              this.$modal.msgSuccess("修改成功");
              this.fileList = []
              this.resetForm('fileForm')
              this.closeDelDialog()
            })
          }
        }
      })
    },
    //取消
    closeDelDialog() {
      this.value = []; //清空上传文件的列表数据
      this.$emit("closeDelDialog")
    },


    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      this.$modal.loading("正在上传文件，请稍候...");
      this.list = [];
      this.number++;
      console.log(this.number)
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {
      this.list.push(res)
      if (res.code == 500) {
        this.$modal.msgError(res.msg);
      }
      var dataArr = [];
      if (this.list.length == this.number) {  //判断上传数据是不是最后一条
        dataArr = this.list;
        this.number = 0;
        var data = dataArr.filter(item => { return item.code == "200" })
        data.map((item,index) => {
          /** 这时只需要push进带有response的数据就好 */
          if (item.code === 200) {
            this.fileList.push({
              fieldName: item.data.fieldName,
              docFileSize: item.data.docFileSize,
              docFileType: this.getType(item.data.fieldName),
              path: item.data.path,
              index: index
            })
          }
        })
        this.$modal.closeLoading();
      }
    },
    // 获取文件类型
    getType(fileName) {
      let arr = fileName.split('.');
      let result = arr.pop();
      return result;
    },
    delTap(row) {
      let index = this.fileList.map(item => item.index).indexOf(row.index);
      console.log(index)
      if(index > -1) {
        this.fileList.splice(index, 1);
      }
      if (this.fileList.length > 0) {
        for (let i = 0; i < this.fileList.length; i++) {
          this.fileList[i].index = i
        }
      }
      console.log(this.fileList)
    },
    onPreviewTap(row) {
      this.item = {
        DOC_FILE_TYPE: row.docFileType,
        path: row.path
      } //文件预览显示第一个
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px 10px !important;
}

.contain {
  width: 100%;
  height: 770px;
  border: 1px solid #DCDFE6;
}

.leftMain {
  overflow: auto;
  //height: 485px;
}

.upLoadMain {
  margin-top: 20px;
  margin-left: 40px;

  button {
    margin-left: 20px;
  }
}

.margin_top {
  margin-top: 20px;
}

::v-deep .el-dialog {
  margin: 30px auto 0 !important;
}
</style>
